<template>
  <el-container class="common-layout">
    <el-header style="background-color:cornflowerblue; color: white;  padding: 10px 20px;">
      <div style="display: flex;">
        <div>
          <el-button type="primary" @click="userLoginFirstPage" v-if="!isLoginFirstPage">登录</el-button>
          <div v-else>
            <div>用户姓名 : <strong>{{ userInfo.userName }}</strong></div>
            <div>
              <el-dropdown placement="bottom-end">
                <span class="el-dropdown__box">
                  <el-icon>
                    <CaretBottom/>
                  </el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="profile" :icon="User"
                                      @click="switchUserInfo">基本资料
                    </el-dropdown-item>
                    <el-dropdown-item command="profile" :icon="List"
                                      @click="switchOrder">订单管理
                    </el-dropdown-item>
                    <el-dropdown-item command="logout" :icon="SwitchButton"
                                      @click="userLoginOut">退出登录
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </div>
        <div style="margin-left:320px">
          <el-input
              v-model="searchQuery"
              style="max-width: 600px"
              placeholder="请按规则输入查询内容"
              class="input-with-select"
          >
            <template #prepend>
              <el-select v-model="select" placeholder="请选择查询规则" style="width: 115px">
                <el-option label="按商品名称或者关键字查询" value="1"/>
                <el-option label="按价格区间查询，~，例如，小于500为~500，大于500为500~,大于200小于500为200~500" value="2"/>
              </el-select>
            </template>
            <template #append>
              <el-button :icon="Search" @click="search"/>
            </template>
          </el-input>
        </div>
        <el-button plain size="small" @click="clearSearch"
                   style="margin-left: 10px;margin-top: 5px">重置
        </el-button>
      </div>

    </el-header>
    <el-main>
      <div class="product-list">
        <div v-for="product in products" :key="product.productId" class="product-item"
             @click="onDetailPage(product.productId)">
          <img :src="product.productImg"
               alt="Product Image" class="product-image">
          <div class="product-info">
            <h3>{{ product.productName }}</h3>
            <p>售价: {{ product.sellingPrice / 100 }}</p>
            <p>库存: {{ product.stock }}</p>
          </div>
        </div>
      </div>
      <el-pagination
          background
          layout="prev, pager, next"
          :page-size="pageSize"
          :total="totalProducts"
          @current-change="handlePageChange"
      />
    </el-main>
  </el-container>
  <userLoginDialog
      :dialog-visible="isLoginDialogVisible"
      @update:dialogVisible="val => isLoginDialogVisible = val"
      @formSubmitted="summitted"
  ></userLoginDialog>
</template>
<script setup>
import {onMounted, ref} from 'vue';
import {useRouter} from 'vue-router';
import {getUserInfo} from '@/api/user.js'
import {getProduct, getProductByNameLike, getProductByMarkerPriceScope} from '@/api/product.js';
import {isLoginStore, useTokenStore} from "@/store/tokenStore.js";
import {ElButton, ElMessage} from "element-plus";
import userLoginDialog from "@/components/dialog/userLoginDialog.vue"
import {CaretBottom, List, Search, SwitchButton, User} from "@element-plus/icons-vue";

const searchQuery = ref('')
const select = ref('')
const router = useRouter();
const products = ref([]);
const currentPage = ref(1);
const pageSize = 6;
const totalProducts = ref(0);
const isLoginDialogVisible = ref(false)
const isLoginFirstPage = ref(false)
const isLogin = isLoginStore()
const userInfo = ref({
      userId: null,
      userName: "",
      phone: "",
      address: ""
    }
)
const search = async () => {
  if (searchQuery.value !== '' && select !== '') {
    if (select.value === '1') {
      getLikeName()
    } else if (select.value === '2') {
      getPriceScope()
    } else {
      ElMessage({
        showClose: true,
        message: '请选择查询规则',
        type: 'error',
      })
    }
  } else {
    ElMessage({
      showClose: true,
      message: '请输入查询内容',
      type: 'error',
    })
  }
}
const switchOrder = () => {
  router.push('/order')
}
const getPriceScope = async () => {
  const priceScopeList = searchQuery.value.split('~')
  if (searchQuery.value.includes('~')) {
    if (priceScopeList[0] !== '' && priceScopeList[1] !== '') {
      const response = await getProductByMarkerPriceScope(currentPage.value, pageSize,
          priceScopeList[0], priceScopeList[1])
      products.value = response.list;
      totalProducts.value = response.totalNum;
    } else if (priceScopeList[0] === '') {
      const response = await getProductByMarkerPriceScope(currentPage.value, pageSize,
          -1, priceScopeList[1])
      products.value = response.list;
      totalProducts.value = response.totalNum;
    } else if (priceScopeList[1] === '') {
      const response = await getProductByMarkerPriceScope(currentPage.value, pageSize,
          priceScopeList[0], -1)
      products.value = response.list;
      totalProducts.value = response.totalNum;
    }
  } else {
    ElMessage({
      showClose: true,
      message: '请按规则输入查询内容，是否缺失了~',
      type: 'error',
    })
  }
}
const getLikeName = async () => {
  const response = await getProductByNameLike(searchQuery.value, currentPage.value, pageSize)
  products.value = response.list
  totalProducts.value = response.totalNum
}
const clearSearch = () => {
  searchQuery.value = '';
  fetchProducts();
}
onMounted(() => {
  fetchProducts()
  isLoginFirstPage.value = isLogin.isLogin
  if (useTokenStore().token !== '') {
    getUserInfoFirstPage()
  }
});
const switchUserInfo = () => {
  router.push('/userInfo')
}
const userLoginOut = () => {
  isLogin.resetLogin(false)
  isLoginFirstPage.value = isLogin.isLogin
  useTokenStore().clearToken()
  ElMessage({
    showClose: true,
    message: '退出登录成功',
    type: 'success',
  })
}
const getUserInfoFirstPage = async () => {
  userInfo.value = await getUserInfo()
}
const summitted = async () => {
  isLogin.resetLogin(true)
  getUserInfoFirstPage()
  isLoginFirstPage.value = isLogin.isLogin
}
const fetchProducts = async () => {
  const response = await getProduct(currentPage.value, pageSize);
  products.value = response.list; // 假设响应数据在 response.data 中
  totalProducts.value = response.totalNum; // 假设总产品数量在 response.total 中
}
const handlePageChange = async (page) => {
  currentPage.value = page;
  fetchProducts();
  // console.log('currentPage:', products.value)
}
const onDetailPage = (productId) => {
  router.push(`/productDetail/${productId}`)
}
const userLoginFirstPage = () => {
  isLoginDialogVisible.value = true
}
</script>


<style scoped>
.common-layout {
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
  overflow-x: hidden;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.el-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.input-with-select {
  border-radius: 25px;
  overflow: hidden;
}

.product-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 20px;
}

.product-item {
  width: calc(33.33% - 20px);
  margin-bottom: 20px;
  cursor: pointer;
  border: 1px solid #ddd;
  padding: 15px;
  box-sizing: border-box;
  background: white;
  border-radius: 10px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.product-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 8px;
}

.product-info {
  margin-top: 15px;
  text-align: center;
}

.product-info h3 {
  font-size: 18px;
  margin: 0 0 10px;
  color: #333;
}

.product-info p {
  margin: 8px 0;
  font-size: 14px;
  color: #666;
}

.el-pagination {
  margin-top: 20px;
  justify-content: center;
}
</style>
